package com.mti.zhpt.shared.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.mti.zhpt.shared.websocket.encoder.ServerEncoder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ServerEndpoint(value = "/websocket/event", encoders = { ServerEncoder.class })
@Component
public class EventWebSocket {
	private static CopyOnWriteArraySet<EventWebSocket> webSocketSet = new CopyOnWriteArraySet<EventWebSocket>();
	private Session session;

	@OnOpen
	public void onOpen(Session session) throws IOException {
		log.debug("onOpen");
		this.session = session;
		webSocketSet.add(this);
	}

	@OnClose
	public void onClose() throws IOException {
		webSocketSet.remove(this);
		log.debug("onClose");
	}

	@OnMessage
	public void onMessage(String message) throws IOException {
		log.debug("onMessage" + message);
	}

	@OnError
	public void onError(Session session, Throwable error) {
		log.debug("onError");
		error.printStackTrace();
	}

	public void sendObject(Object data) {
		log.debug("sendObject");
		try {
			this.session.getBasicRemote().sendObject(data);
		} catch (IOException | EncodeException e) {
			log.debug("发送消息出现错误");
			log.error(e.getMessage());
		}
	}

	public static void sendInfo(Object data) throws IOException {
		for (EventWebSocket item : webSocketSet) {
			item.sendObject(data);
		}
	}

}